package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {
    @Autowired
    private DeptService deptService;
    @Autowired
    private EmpExprMapper empExprMapper;
    /**
     * 条件分页查询员工信息
     *
     * @param param@return
     */
    @Override
    public PageResult findPage(EmpQueryParam param) {

        //1.设置分页参数
        IPage<Emp> pageinfo = new Page<>(param.getPage(),param.getPageSize());
        //2.查询条件构造器
        LambdaQueryWrapper<Emp> queryWrapper = Wrappers.<Emp>lambdaQuery()
                .like(param.getName() != null,Emp::getName,param.getName())     //姓名
                .eq(param.getGender() != null,Emp::getGender,param.getGender())   //性别
                .between(param.getBegin() != null && param.getEnd()!= null,Emp::getEntryDate,param.getBegin(),param.getEnd())  //入职时间
                .orderByDesc(Emp::getUpdateTime);    //按照更新时间倒序排序

        //3.调用分页方法
        IPage<Emp> result = this.page(pageinfo,queryWrapper);
        List<Emp> empList = result.getRecords();  //员工信息
        long total = result.getTotal();           //总条数
        if (!CollectionUtils.isEmpty(empList)) {
            //4.获取部门id集合
            List<Long> deptIdList = empList.stream().map(emp -> emp.getDeptId()).toList();
            //5.部门id集合去重
            deptIdList = deptIdList.stream().distinct().toList();
            //6.根据部门id集合查询部门列表
            List<Dept> deptList = deptService.listByIds(deptIdList);
            //7.双重循坏，给每个员工的部门名称赋值
            empList.forEach(emp -> {
                deptList.stream().filter(dept -> dept.getId().equals(emp.getDeptId()))
                        .findFirst()
                        .ifPresent(dept -> emp.setDeptName(dept.getName()));
            });
        }
        return new PageResult(total, empList);
    }


    /**
     * 新增员工
     *
     * @param emp
     */
    @Override
    @Transactional
    public void saveEmp(Emp emp) {
        //1.新增员工表
        emp.setPassword("123456");
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        this.save(emp);
        //2.新增员工工作经历表
        List<EmpExpr> exprList = emp.getExprList();
        if(!CollectionUtils.isEmpty(exprList)){
            //3.遍历员工工作经历列表,设置员工id
            exprList.forEach(expr -> expr.setEmpId(emp.getId()));
            empExprMapper.insert(exprList);
        }
    }

    /**
     * 根据id查询员工信息
     *
     * @param id
     * @return
     */
    @Override
    public Emp getEmpById(long id) {
        //1.查询员工信息
        Emp emp = this.getById(id);
        //2.查询员工工作经历信息
        List<EmpExpr> empExprs = empExprMapper.selectList(Wrappers.<EmpExpr>lambdaQuery().eq(EmpExpr::getEmpId, emp.getId()));
        //3.封装员工信息
        emp.setExprList(empExprs);
        return emp;
    }

    /**
     * 修改员工
     *
     * @param emp
     */
    @Override
    @Transactional
    public void updateEmp(Emp emp) {
        //1.修改员工表
        emp.setUpdateTime(LocalDateTime.now());
        this.updateById(emp);
        //2.修改员工工作经历表
        //2.1.删除员工工作经历表
        List<EmpExpr> empExprs = empExprMapper.selectList(Wrappers.<EmpExpr>lambdaQuery().eq(EmpExpr::getEmpId, emp.getId()));
        empExprMapper.deleteByIds(empExprs);
        //2.2新增员工工作经历表
        List<EmpExpr> exprList = emp.getExprList();
        if(!CollectionUtils.isEmpty(exprList)){
            exprList.forEach(expr -> expr.setEmpId(emp.getId()));
            empExprMapper.insert(exprList);
        }
    }

    /**
     * 删除 员工
     *
     * @param ids
     */
    @Override
    @Transactional
    public void deleteEmpById(List<Integer> ids) {
        //1.删除员工表
        this.removeBatchByIds(ids);
        //2.删除员工工作经历表
        empExprMapper.delete(Wrappers.<EmpExpr>lambdaQuery().in(EmpExpr::getEmpId,ids));
    }

}
